package com.xm.xmapp.tool;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.media.ExifInterface;
import android.util.Base64;

import com.xm.xmapp.R;
import com.xm.xmapp.app.CodeConstant;
import com.xm.xmapp.app.MyAppcation;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class ImageTool {

	public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
			double newHeight) {
		// 获取这个图片的宽和高
		float width = bgimage.getWidth();
		float height = bgimage.getHeight();
		// 创建操作图片用的matrix对象
		Matrix matrix = new Matrix();
		// 计算宽高缩放率
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;

		float scale;

		if (scaleWidth > scaleHeight)
			scale = scaleWidth;
		else
			scale = scaleHeight;

		// 缩放图片动作
		matrix.postScale(scale, scale);
		Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
				(int) height, matrix, true);

		return saveBitmapfile(bitmap);
	}

	private static Bitmap rotateBitmap(Bitmap bitmap, int rotate) {
		if (bitmap == null)
			return null;

		int w = bitmap.getWidth();
		int h = bitmap.getHeight();

		// Setting post rotate to 90
		Matrix mtx = new Matrix();
		mtx.postRotate(rotate);
		return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
	}

	private static int readPictureDegree(String path) {
		int degree = 0;
		try {
			ExifInterface exifInterface = new ExifInterface(path);
			int orientation = exifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270;
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return degree;
	}

	private static int calculateInSampleSize(Options options,
			int reqWidth, int reqHeight) {
		// Raw height and width of image
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {

			// Calculate ratios of height and width to requested height and
			// width
			final int heightRatio = Math.round((float) height
					/ (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);

			// Choose the smallest ratio as inSampleSize value, this will
			// guarantee
			// a final image with both dimensions larger than or equal to the
			// requested height and width.
			inSampleSize = (heightRatio < widthRatio ? widthRatio : heightRatio) + 1;
		}

		return inSampleSize;
	}

	public static Bitmap getSmallBitmap(String filePath, int w, int h) {

		final Options options = new Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filePath, options);
		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, w, h);
//		options.inPreferredConfig =  Bitmap.Config.RGB_565;
		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;
		Bitmap bm = BitmapFactory.decodeFile(filePath, options);
		if (bm == null) {
			return null;
		}
		int degree = readPictureDegree(filePath);
		bm = rotateBitmap(bm, degree);

		return saveBitmapfile(bm);

	}

	/**
	 * 通过Base32将Bitmap转换成Base64字符串
	 * 
	 * @param bit
	 * @return
	 */
	public static String Bitmap2StrByBase64(Bitmap bit) {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		bit.compress(CompressFormat.JPEG, 100, bos);// 参数100表示不压缩
		byte[] bytes = bos.toByteArray();
		return Base64.encodeToString(bytes, Base64.DEFAULT);
	}

	public static Bitmap saveBitmapfile(Bitmap bmp) {
		CompressFormat format = CompressFormat.JPEG;
		int quality = 70;
		OutputStream stream = null;
		try {
			stream = new FileOutputStream(CodeConstant.PhotoPath);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		bmp.compress(format, quality, stream);
		return bmp;
	}

//	public static int getImgHeight() {
//		Bitmap photo = BitmapFactory.decodeResource(MyAppcation
//				.getMyAppcation().getResources(), R.mipmap.pingjia_touxiang);
//		return photo.getHeight();
//
//	}

	public static Bitmap getBitmap(String str, Context activity, int i) {

		String key = str + i;
		Bitmap icon = MyCache.getMyCache().getBitmapCache(key);
		if (icon == null) {
			Bitmap photo = BitmapFactory.decodeResource(
					activity.getResources(), i);
			int width = photo.getWidth(), hight = photo.getHeight();
			icon = Bitmap.createBitmap(width, hight, Bitmap.Config.ARGB_8888); // 建立一个空的BItMap
			Canvas canvas = new Canvas(icon);// 初始化画布绘制的图像到icon上
			Paint photoPaint = new Paint(); // 建立画笔
			photoPaint.setDither(true); // 获取跟清晰的图像采样
			photoPaint.setFilterBitmap(true);// 过滤一些
			Rect src = new Rect(0, 0, photo.getWidth(), photo.getHeight());// 创建一个指定的新矩形的坐标
			Rect dst = new Rect(0, 0, width, hight);// 创建一个指定的新矩形的坐标
			canvas.drawBitmap(photo, src, dst, photoPaint);// 将photo 缩放或则扩大到
															// dst使用的填充区photoPain
			Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG
					| Paint.DEV_KERN_TEXT_FLAG);// 设置画笔
			float margin_top = AndroidTool.dp2px(10);
			textPaint.setTextSize(margin_top);// 字体大小
			textPaint.setTypeface(Typeface.DEFAULT_BOLD);// 采用默认的宽度
			textPaint.setColor(Color.WHITE);// 采用的颜色
			textPaint.setTextAlign(Align.CENTER);

			canvas.drawText(str, width * 11 / 15, hight / 4, textPaint);// 绘制上去字，开始未知x,y采用那只笔绘制
			canvas.save(Canvas.ALL_SAVE_FLAG);
			canvas.restore();
			MyCache.getMyCache().putBitmapCache(key, icon);
		}
		return icon;

	}

	public static Bitmap getNewBitmap(int str1, int str2, Context activity,
			int i) {
		String key = str1 + "_" + str2 + "_" + i;
		Bitmap icon = MyCache.getMyCache().getBitmapCache(key);
		if (icon == null) {

			Bitmap photo = BitmapFactory.decodeResource(
					activity.getResources(), i);
			int width = photo.getWidth(), hight = photo.getHeight();
			icon = Bitmap.createBitmap(width, hight, Bitmap.Config.ARGB_4444); // 建立一个空的BItMap
			Canvas canvas = new Canvas(icon);// 初始化画布绘制的图像到icon上
			Paint photoPaint = new Paint(); // 建立画笔
			photoPaint.setDither(true); // 获取跟清晰的图像采样
			photoPaint.setFilterBitmap(true);// 过滤一些
			Rect src = new Rect(0, 0, photo.getWidth(), photo.getHeight());// 创建一个指定的新矩形的坐标
			Rect dst = new Rect(0, 0, width, hight);// 创建一个指定的新矩形的坐标
			canvas.drawBitmap(photo, src, dst, photoPaint);// 将photo 缩放或则扩大到 //
															// dst使用的填充区photoPain

			float margin_top;
			Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG
					| Paint.DEV_KERN_TEXT_FLAG);// 设置画笔

			textPaint.setTypeface(Typeface.DEFAULT_BOLD);// 采用默认的宽度
			textPaint.setTextAlign(Align.CENTER);

			margin_top = AndroidTool.dp2px(17);
			textPaint.setTextSize(margin_top);
			textPaint.setColor(Color.YELLOW);
			
			int width1,width2;
		
			
			if(str1>=10)
			{
				width1 = width * 41 / 134;
				
			}
			else
			{
				width1 = width * 61 / 134;
			}
			
			if(str2 >=10)
			{
				width2 = width * 87 / 134;
			
			}else
			{
				width2 = width * 97 / 134;
				
			}
			
			
			canvas.drawText(str1 + "", width1, hight * 81 / 134,
					textPaint);// 绘制上去字，开始未知x,y采用那只笔绘制
			
			
			textPaint.setColor(Color.WHITE);// 采用的颜色
			margin_top = AndroidTool.dp2px(8);
			textPaint.setTextSize(margin_top);// 字体大小
			
			
			canvas.drawText(str2 + "", width2, hight * 107 / 134,
					textPaint);// 绘制上去字，开始未知x,y采用那只笔绘制
			
			
			canvas.save(Canvas.ALL_SAVE_FLAG);
			canvas.restore();
			MyCache.getMyCache().putBitmapCache(key, icon);
		}
		return icon;

	}

	// public static Bitmap getBitmap3(String str, Context activity, int i) {
	// Bitmap photo = BitmapFactory.decodeResource(activity.getResources(), i);
	// int width = photo.getWidth(), hight = photo.getHeight();
	// Bitmap icon = Bitmap
	// .createBitmap(width, hight, Bitmap.Config.ARGB_8888); // 建立一个空的BItMap
	// Canvas canvas = new Canvas(icon);// 初始化画布绘制的图像到icon上
	// Paint photoPaint = new Paint(); // 建立画笔
	// photoPaint.setDither(true); // 获取跟清晰的图像采样
	// photoPaint.setFilterBitmap(true);// 过滤一些
	// Rect src = new Rect(0, 0, photo.getWidth(), photo.getHeight());//
	// 创建一个指定的新矩形的坐标
	// Rect dst = new Rect(0, 0, width, hight);// 创建一个指定的新矩形的坐标
	// canvas.drawBitmap(photo, src, dst, photoPaint);// 将photo 缩放或则扩大到
	// // dst使用的填充区photoPain
	// Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG
	// | Paint.DEV_KERN_TEXT_FLAG);// 设置画笔
	// float margin_top = activity.getResources().getDimension(R.dimen.dp10);
	// textPaint.setTextSize(margin_top);// 字体大小
	// textPaint.setTypeface(Typeface.DEFAULT_BOLD);// 采用默认的宽度
	// textPaint.setColor(Color.WHITE);// 采用的颜色
	//
	// int mStringWidth = (int) textPaint.measureText(str);
	// int mStringHight = (int) (textPaint.ascent() + textPaint.descent());
	//
	// // textPaint.setTextAlign(Align.CENTER);
	// float margin_left = activity.getResources().getDimension(R.dimen.dp5);
	// canvas.drawText(str, width - mStringWidth - margin_left, hight / 5
	// - mStringHight / 2, textPaint);// 绘制上去字，开始未知x,y采用那只笔绘制
	// canvas.save(Canvas.ALL_SAVE_FLAG);
	// canvas.restore();
	// return icon;
	// }

	/** 保存图片到本应用下 **/
	public static void savePicture(String fileName, Bitmap bitmap) {

		FileOutputStream fos = null;
		try {// 直接写入名称即可，没有会被自动创建；私有：只有本应用才能访问，重新内容写入会被覆盖
			fos = MyAppcation.getMyAppcation().openFileOutput(fileName,
					Context.MODE_PRIVATE);
			bitmap.compress(CompressFormat.JPEG, 100, fos);// 把图片写入指定文件夹中

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != fos) {
					fos.close();
					fos = null;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 压缩已存在的图片对象，并返回压缩后的图片
	 * 
	 * @param bitmap
	 * @param reqsW
	 * @param reqsH
	 * @return
	 */
	public final static Bitmap compressBitmap(Bitmap bitmap, int reqsW,
			int reqsH) {
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			bitmap.compress(CompressFormat.PNG, 100, baos);
			byte[] bts = baos.toByteArray();
			Bitmap res = compressBitmap(bts, reqsW, reqsH);
			baos.close();
			return res;
		} catch (IOException e) {
			
			e.printStackTrace();
			return bitmap;
		}
	}

	/**
	 * 压缩指定byte[]图片，并得到压缩后的图像
	 * 
	 * @param bts
	 * @param reqsW
	 * @param reqsH
	 * @return
	 */
	public final static Bitmap compressBitmap(byte[] bts, int reqsW, int reqsH) {
		final Options options = new Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeByteArray(bts, 0, bts.length, options);
		options.inSampleSize = caculateInSampleSize(options, reqsW, reqsH);
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeByteArray(bts, 0, bts.length, options);
	}

	/**
	 * caculate the bitmap sampleSize
	 *
	 * @return
	 */
	public final static int caculateInSampleSize(Options options,
			int rqsW, int rqsH) {
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;
		if (rqsW == 0 || rqsH == 0)
			return 1;
		if (height > rqsH || width > rqsW) {
			final int heightRatio = Math.round((float) height / (float) rqsH);
			final int widthRatio = Math.round((float) width / (float) rqsW);
			inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
		}
		return inSampleSize;
	}

	public static Bitmap getBitmap1(String str, Context activity, int i) {

		String key = str + i;
		Bitmap icon = MyCache.getMyCache().getBitmapCache(key);

		if (icon == null) {
			Bitmap photo = BitmapFactory.decodeResource(
					activity.getResources(), i);
			int width = photo.getWidth(), hight = photo.getHeight();
			icon = Bitmap.createBitmap(width, hight, Bitmap.Config.ARGB_4444); // 建立一个空的BItMap
			Canvas canvas = new Canvas(icon);// 初始化画布绘制的图像到icon上
			Paint photoPaint = new Paint(); // 建立画笔
			photoPaint.setDither(true); // 获取跟清晰的图像采样
			photoPaint.setFilterBitmap(true);// 过滤一些

			Rect src = new Rect(0, 0, photo.getWidth(), photo.getHeight());// 创建一个指定的新矩形的坐标
			Rect dst = new Rect(0, 0, width, hight);// 创建一个指定的新矩形的坐标
			canvas.drawBitmap(photo, src, dst, photoPaint);// 将photo 缩放或则扩大到
															// dst使用的填充区photoPaint

			Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG
					| Paint.DEV_KERN_TEXT_FLAG);// 设置画笔
			textPaint.setTypeface(Typeface.MONOSPACE);// 采用默认的宽度
			textPaint.setColor(Color.WHITE);// 采用的颜色

			float margin_top = AndroidTool.dp2px(15);
			textPaint.setTextSize(margin_top);// 字体大小
			int mStringWidth = (int) textPaint.measureText(str);
			for (int j = 0; j < margin_top; j++) {

				if (width > mStringWidth) {
					break;
				} else {
					textPaint.setTextSize(margin_top--);
					mStringWidth = (int) textPaint.measureText(str);
				}

			}

			int mStringHight = (int) (textPaint.ascent() + textPaint.descent());
			canvas.drawText(str, width / 2 - mStringWidth / 2, hight / 2
					- mStringHight / 2, textPaint);// 绘制上去字，开始未知x,y采用那只笔绘制
			canvas.save(Canvas.ALL_SAVE_FLAG);
			canvas.restore();

			MyCache.getMyCache().putBitmapCache(key, icon);
		}
		return icon;
	}

	public static Bitmap zoomBitmap(Bitmap bitmap, int i, int j) {
		
		return null;
	}
}
